package P94.P102;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author DJ同学
 * @Date 2021/2/22 22:54
 * @Version 1.0
 * @Name 二叉树的层序遍历
 * @Problem https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * @Idea BFS + 直接使用两层循坏
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root==null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            //获得当前层的数量
            int cnt = queue.size();
            //保存当前层节点数组
            List<Integer> temp = new ArrayList<>();
            //获得当前层
            for(int i = 0;i<cnt;i++){
                //添加节点
                TreeNode cur = queue.peek();
                temp.add(cur.val);
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
                //弹出当前节点
                queue.poll();
            }
            res.add(temp);
        }
        return res;
    }
}
